/**
 * Copyright (c) 2021 Sunshine Insurance Group Inc
 * Created by zhaochengxin on 2021/6/18 0018.
 */
package flex.cc.vehicle_svr.util;


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * 上游师傅坐标接口加密解密类
 * @author dupenghui
 * @date 20211215
 */
public class UpPointsApiAesEcb {
    private SecretKeySpec sks;
    private String insType;
    public static final String DEFAULT_INS_TYPE = "AES/ECB/PKCS5Padding";

    public UpPointsApiAesEcb(byte[] key) throws Exception {
        this(key, "AES/ECB/PKCS5Padding");
    }

    public UpPointsApiAesEcb(byte[] key, String insType) throws Exception {
        this.sks = null;
        this.insType = null;
        if (key == null) {
            throw new NullPointerException("Please input key with valid value");
        } else {
            byte[] newKey = new byte[16];

            for(int i = 0; i < key.length; ++i) {
                newKey[i % 16] ^= key[i];
            }

            this.sks = new SecretKeySpec(newKey, "AES");
            this.insType = insType;
        }
    }

    public byte[] encrypt(String content) throws Exception {
        return this.encrypt(content.getBytes(StandardCharsets.UTF_8));
    }

    public byte[] encrypt(byte[] byteContent) throws Exception {
        Cipher encrypter = Cipher.getInstance(this.insType);
        encrypter.init(1, this.sks);
        return encrypter.doFinal(byteContent);
    }

    public byte[] decrypt(byte[] content) throws Exception {
        Cipher decrypter = Cipher.getInstance(this.insType);
        decrypter.init(2, this.sks);
        return decrypter.doFinal(content);
    }

}
